﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Xenta.Attributes;
using Xenta.Utils;
using Xenta.Web.Controllers;

namespace Xenta.Web.Areas.Wizard.Controllers
{
    [Authenticate]
    public sealed class InvoiceController : ExtController
    {
        #region GET/POST Actions

        [HttpGet, PersistState]
        public ActionResult PdfReport(int id)
        {
            var m = Svc.ProcessOperation("GetInvoice", new
            {
                EntityID = id
            }, new
            {
                DisclosureLevel = "Base"
            });
            if(m == null)
                return HttpNotFound();

            var o = Svc.ProcessOperation("GetOrder", new
            {
                EntityID = JDM.Int32(m.Order.EntityID)
            }, new
            {
                DisclosureLevel = "Base"
            });
            if(JDM.Int32(o.Customer.EntityID) != JDM.Int32(Svc.Customer.EntityID))
                return new HttpUnauthorizedResult();
            try
            {
                long rptElapsedTime = 0;
                string rptMimeType = String.Empty;
                var rptData = Svc.BuildReport("InvoicePdfReport",
                    new Dictionary<String, String>
                    {
                        {"invoiceID", JDM.String(m.EntityID)},
                        {"locale", JDM.String(Svc.Localization.Code)}
                    },
                    out rptMimeType,
                    out rptElapsedTime);
                string dwlExt = MimeTypeHelper.TypeToExt(rptMimeType);
                string dwlName = String.Format("invoice_{0}_{1}.{2}", JDM.String(m.EntityID), JDM.String(m.Guid), dwlExt);
                return File(rptData, rptMimeType, dwlName);
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Show").Ctrl("Order").Set(new
            {
                id = JDM.Int32(m.Order.EntityID)
            }).Localized());
        }

        #endregion

        #region Child Actions

        [ChildActionOnly]
        public ActionResult _Grid(int orderID)
        {
            var m = Svc.ProcessOperation("SearchInvoices", new
            {
                OrderID = orderID
            }, new
            {
                DisclosureLevel = "Base"
            });
            return PartialView(m);
        }

        [ChildActionOnly]
        public ActionResult _Overview(int id)
        {
            var m = Svc.ProcessOperation("GetInvoice", new
            {
                EntityID = id
            }, new
            {
                DisclosureLevel = "Base"
            });
            return PartialView(m);
        }

        #endregion
    }
}
